package com.zlz.open.ugs.util;

import com.zlz.open.ugs.exchange.request.UgsRequest;
import org.eclipse.jetty.util.StringUtil;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: zhulinzhong
 * @Date: 2024/6/3
 */
public class RequestParserUtil {

    public static Map<String, Object> parse(UgsRequest request, String boundary) {
        Map<String, Object> result = new HashMap<>();
        String[] lines = request.getBody().toString().split(boundary);
        for (String s : lines) {
            String line = s.trim();
            if (!line.startsWith("Content-Disposition")) {
                continue;
            }
            int typeSp = line.indexOf(";");
            String body = line.substring(typeSp + 1).trim();
            if (body.contains("; filename=")) {
                int filedSp = body.indexOf(";");
                String substring = body.substring(filedSp + 1);
                String fileName = substring.substring(0,substring.indexOf("\r\n"));
                substring = substring.replace(fileName,"");
                String contentType = substring.substring(0,substring.indexOf("\r\n\r\n"));
                String data = substring.substring(substring.indexOf("\";")+2);
                request.getBody().shift(fileName, contentType, data);
            } else if (body.startsWith("name")) {
                int formDataSp = body.indexOf("\r\n\r\n");
                String key = body.substring(6, formDataSp);
                String value = body.substring(formDataSp + 1).trim();
                if (StringUtil.isEmpty(value)) {
                    continue;
                }
                Object values = result.get(key);
                if (values == null) {
                    result.put(key, value);
                    continue;
                }
                if (values instanceof Object[]) {
                    Object[] vals = (Object[]) values;
                    Object[] newArray = Arrays.copyOf(vals, vals.length + 1);
                    newArray[newArray.length - 1] = value;
                    result.put(key, newArray);
                    continue;
                }
                result.put(key, new Object[]{values, value});
            }
        }
        return result;
    }
}
